#include "Config.h"
#include "wch/Thread.h"
#include "MsgHandler/MsgTypes.h"
#include "MsgHandler/MsgPool.h"
#include "Common/Atoi.h"
#include "Common/Itoa.h"
#include "Common/TimeUtil.h"
#include "Server.h"
#include "Network/Network.h"
#include "TcpServerWrapper.h"
#include "LogicWorker.h"
#include "Server/ServerType.h"
#include "Cfg.h"
#include "Server/IDGenerator.h"
#include "Game/GameManager.h"

const char * s_HelpInfo = "";
UInt8 SERVER_TYPE = 0;
UInt32 SERVER_ID = 0;
std::string SERVER_NAME;

Server::Server() : _logicWorker( nullptr ), _tcpService( nullptr )
{

}

Server::~Server()
{
	SAFE_DELETE( _logicWorker );
	SAFE_DELETE( _tcpService );
}

bool Server::init()
{
	Network::Initialize();
	TimeUtil::Init();
	cfg.load( getFilePath( "conf/config-game.lua" ) );
	MSGPOOL().init( THREAD_COUNT );
	//
	_gameManager = new GameManager();
	//
	_logicWorker = WorkerThread<LogicWorker>::Clone( new LogicWorker( Thread_Logic ) );
	_tcpService = new Network::TcpServerWrapper( cfg.getTcpPort(), 1 );
	return true;
}

void Server::run()
{
	_logicWorker->Run();
	_tcpService->Start();
	_tcpService->Join();
	fprintf(stdout, "Server Start Success~\n");
}

void Server::shutdown()
{
	_tcpService->UnInit();
	wch::Thread::sleep( 2000 );
	_logicWorker->Shutdown();
}

void Server::unInit()
{
	MSGPOOL().unInit();
	Network::Uninitialize();
}

bool Server::parseCommandInfo( Int32 argc, char * argv[] )
{
	SERVER_TYPE = Server_Hall;
	if ( argc >= 2  )
	{
		SERVER_ID = Atoi<UInt16>(argv[1]);
		SERVER_NAME = "Hall";
		SERVER_NAME.append( Itoa<UInt16>(SERVER_ID) );
	}
	else
	{
		SERVER_ID = 1;
		SERVER_NAME = "Hall";
		SERVER_NAME.append( Itoa<UInt16>(SERVER_ID) );
	}
	return true;
}

std::string& Server::getWorkDirectory()
{
	return _workerDirectory;
}

std::string Server::getFilePath( const std::string& path )
{
	std::string fullPath = _workerDirectory;
	fullPath.append( path );
	return fullPath;
}